<template>
  <div class="course-list">
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
      <h2>我的课程</h2>
          <p>管理您的所有课程内容</p>
        </div>
        <div class="header-actions">
      <a-button type="primary" @click="createCourse">
        <PlusOutlined />
        创建课程
      </a-button>
        </div>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <a-card class="search-card" :bordered="false">
      <a-form layout="inline" :model="searchForm" @finish="handleSearch">
        <a-row :gutter="16" style="width: 100%">
          <a-col :span="6" :xs="24" :sm="12" :md="6">
            <a-form-item>
          <a-input
            v-model:value="searchForm.keyword"
            placeholder="搜索课程名称"
            allow-clear
                :prefix="SearchOutlined"
          />
            </a-form-item>
        </a-col>
          <a-col :span="4" :xs="24" :sm="12" :md="4">
            <a-form-item>
          <a-select
            v-model:value="searchForm.status"
            placeholder="课程状态"
            allow-clear
                style="width: 100%"
          >
            <a-select-option value="draft">草稿</a-select-option>
            <a-select-option value="published">已发布</a-select-option>
            <a-select-option value="offline">已下架</a-select-option>
          </a-select>
            </a-form-item>
        </a-col>
          <a-col :span="4" :xs="24" :sm="12" :md="4">
            <a-form-item>
          <a-select
            v-model:value="searchForm.category"
            placeholder="课程分类"
            allow-clear
                style="width: 100%"
          >
            <a-select-option value="ai">AI技术</a-select-option>
            <a-select-option value="programming">编程开发</a-select-option>
            <a-select-option value="design">设计创意</a-select-option>
                <a-select-option value="data">数据科学</a-select-option>
          </a-select>
            </a-form-item>
        </a-col>
          <a-col :span="6" :xs="24" :sm="12" :md="6">
            <a-form-item>
              <a-space>
                <a-button type="primary" html-type="submit" :loading="searching">
            <SearchOutlined />
            搜索
          </a-button>
                <a-button @click="resetSearch">
                  <ReloadOutlined />
                  重置
                </a-button>
              </a-space>
            </a-form-item>
        </a-col>
      </a-row>
      </a-form>
    </a-card>

    <!-- 课程列表 -->
    <a-card class="list-card" :bordered="false" :loading="loading">
      <template #extra>
        <a-space>
          <a-button @click="refreshData" :loading="refreshing">
            <ReloadOutlined />
            刷新
          </a-button>
          <a-dropdown>
            <a-button>
              批量操作 <DownOutlined />
            </a-button>
            <template #overlay>
              <a-menu @click="handleBatchAction">
                <a-menu-item key="publish">批量发布</a-menu-item>
                <a-menu-item key="offline">批量下架</a-menu-item>
                <a-menu-item key="delete">批量删除</a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </a-space>
      </template>

      <a-table
        :columns="columns"
        :data-source="courseList"
        :loading="loading"
        :pagination="pagination"
        :row-selection="rowSelection"
        @change="handleTableChange"
        :scroll="{ x: 1200 }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'cover'">
            <a-image
              :src="record.cover"
              :width="80"
              :height="60"
              :fallback="defaultCover"
              class="course-cover"
            />
          </template>
          
          <template v-else-if="column.key === 'status'">
            <a-tag :color="getStatusColor(record.status)">
              {{ getStatusText(record.status) }}
            </a-tag>
          </template>
          
          <template v-else-if="column.key === 'price'">
            <span class="price">¥{{ record.price }}</span>
          </template>
          
          <template v-else-if="column.key === 'sales'">
            <div class="sales-info">
              <div class="sales-count">{{ record.sales }}人</div>
              <div class="sales-rate">
                <a-progress 
                  :percent="record.salesRate" 
                  :show-info="false" 
                  size="small"
                  :stroke-color="getSalesColor(record.salesRate)"
                />
              </div>
            </div>
          </template>
          
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="editCourse(record)">
                <EditOutlined />
                编辑
              </a-button>
              <a-button type="link" size="small" @click="viewCourse(record)">
                <EyeOutlined />
                查看
              </a-button>
              <a-dropdown>
                <a-button type="link" size="small">
                  更多 <DownOutlined />
                </a-button>
                <template #overlay>
                  <a-menu @click="handleMenuClick">
                    <a-menu-item key="publish" v-if="record.status === 'draft'">
                      <CheckCircleOutlined />
                      发布
                    </a-menu-item>
                    <a-menu-item key="offline" v-if="record.status === 'published'">
                      <StopOutlined />
                      下架
                    </a-menu-item>
                    <a-menu-item key="copy">
                      <CopyOutlined />
                      复制
                    </a-menu-item>
                    <a-menu-divider />
                    <a-menu-item key="delete" danger>
                      <DeleteOutlined />
                      删除
                    </a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { message, Modal } from 'ant-design-vue'
import {
  PlusOutlined,
  SearchOutlined,
  ReloadOutlined,
  DownOutlined,
  EditOutlined,
  EyeOutlined,
  CheckCircleOutlined,
  StopOutlined,
  CopyOutlined,
  DeleteOutlined
} from '@ant-design/icons-vue'

const router = useRouter()

// 状态管理
const loading = ref(false)
const searching = ref(false)
const refreshing = ref(false)

// 搜索表单
const searchForm = ref({
  keyword: '',
  status: '',
  category: ''
})

// 分页配置
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number, range: [number, number]) => 
    `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
})

// 选中的行
const selectedRowKeys = ref<string[]>([])
const rowSelection = computed(() => ({
  selectedRowKeys: selectedRowKeys.value,
  onChange: (keys: string[]) => {
    selectedRowKeys.value = keys
  }
}))

// 课程列表数据
const courseList = ref([
  {
    key: '1',
    id: 1,
    title: 'AI基础入门课程',
    cover: 'https://via.placeholder.com/80x60/667eea/ffffff?text=AI',
    category: 'AI技术',
    price: 299,
    status: 'published',
    sales: 156,
    salesRate: 78,
    createTime: '2024-01-10',
    updateTime: '2024-01-15'
  },
  {
    key: '2',
    id: 2,
    title: '机器学习实战',
    cover: 'https://via.placeholder.com/80x60/f093fb/ffffff?text=ML',
    category: 'AI技术',
    price: 599,
    status: 'published',
    sales: 89,
    salesRate: 65,
    createTime: '2024-01-08',
    updateTime: '2024-01-14'
  },
  {
    key: '3',
    id: 3,
    title: '前端开发进阶',
    cover: 'https://via.placeholder.com/80x60/4facfe/ffffff?text=FE',
    category: '编程开发',
    price: 399,
    status: 'draft',
    sales: 0,
    salesRate: 0,
    createTime: '2024-01-12',
    updateTime: '2024-01-12'
  }
])

// 表格列定义
const columns = [
  {
    title: '课程封面',
    dataIndex: 'cover',
    key: 'cover',
    width: 100,
    fixed: 'left'
  },
  {
    title: '课程名称',
    dataIndex: 'title',
    key: 'title',
    width: 200,
    ellipsis: true
  },
  {
    title: '分类',
    dataIndex: 'category',
    key: 'category',
    width: 100
  },
  {
    title: '价格',
    dataIndex: 'price',
    key: 'price',
    width: 100
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100
  },
  {
    title: '销量',
    dataIndex: 'sales',
    key: 'sales',
    width: 120
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 120
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
    key: 'updateTime',
    width: 120
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right'
  }
]

// 默认封面
const defaultCover = 'https://via.placeholder.com/80x60/cccccc/ffffff?text=No+Image'

// 获取状态颜色
const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    draft: 'orange',
    published: 'green',
    offline: 'red'
  }
  return colorMap[status] || 'default'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    draft: '草稿',
    published: '已发布',
    offline: '已下架'
  }
  return textMap[status] || '未知'
}

// 获取销量颜色
const getSalesColor = (rate: number) => {
  if (rate >= 80) return '#52c41a'
  if (rate >= 60) return '#1890ff'
  if (rate >= 40) return '#faad14'
  return '#ff4d4f'
}

// 搜索处理
const handleSearch = async () => {
  searching.value = true
  try {
    // 模拟搜索
    await new Promise(resolve => setTimeout(resolve, 500))
    console.log('搜索条件:', searchForm.value)
    message.success('搜索完成')
  } catch (error) {
    message.error('搜索失败')
  } finally {
    searching.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    keyword: '',
    status: '',
    category: ''
  }
  handleSearch()
}

// 刷新数据
const refreshData = async () => {
  refreshing.value = true
  try {
    await new Promise(resolve => setTimeout(resolve, 1000))
    message.success('数据已刷新')
  } catch (error) {
    message.error('刷新失败')
  } finally {
    refreshing.value = false
  }
}

// 表格变化处理
const handleTableChange = (pag: any, filters: any, sorter: any) => {
  pagination.value.current = pag.current
  pagination.value.pageSize = pag.pageSize
  console.log('表格变化:', { pag, filters, sorter })
}

// 批量操作
const handleBatchAction = ({ key }: { key: string }) => {
  if (selectedRowKeys.value.length === 0) {
    message.warning('请选择要操作的课程')
    return
  }

  switch (key) {
    case 'publish':
      Modal.confirm({
        title: '确认发布',
        content: `确定要发布选中的 ${selectedRowKeys.value.length} 门课程吗？`,
        onOk: () => {
          message.success('批量发布成功')
          selectedRowKeys.value = []
        }
      })
      break
    case 'offline':
      Modal.confirm({
        title: '确认下架',
        content: `确定要下架选中的 ${selectedRowKeys.value.length} 门课程吗？`,
        onOk: () => {
          message.success('批量下架成功')
          selectedRowKeys.value = []
        }
      })
      break
    case 'delete':
      Modal.confirm({
        title: '确认删除',
        content: `确定要删除选中的 ${selectedRowKeys.value.length} 门课程吗？此操作不可恢复！`,
        okType: 'danger',
        onOk: () => {
          message.success('批量删除成功')
          selectedRowKeys.value = []
        }
      })
      break
  }
}

// 菜单点击处理
const handleMenuClick = ({ key, keyPath }: { key: string, keyPath: string[] }) => {
  console.log('菜单点击:', key, keyPath)
  // 这里可以实现具体的操作逻辑
}

// 编辑课程
const editCourse = (record: any) => {
  router.push(`/merchant/course/edit/${record.id}`)
}

// 查看课程
const viewCourse = (record: any) => {
  router.push(`/course/${record.id}`)
}

// 创建课程
const createCourse = () => {
  router.push('/merchant/course/create')
}

// 组件挂载时初始化
onMounted(() => {
  loading.value = true
  // 模拟加载数据
  setTimeout(() => {
    loading.value = false
    pagination.value.total = courseList.value.length
  }, 1000)
})
</script>

<style scoped>
.course-list {
  padding: 0;
}

.page-header {
  margin-bottom: 24px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 24px;
}

.header-left h2 {
  font-size: 24px;
  color: #333;
  margin-bottom: 8px;
  font-weight: 600;
}

.header-left p {
  color: #666;
  font-size: 14px;
  margin: 0;
}

.header-actions {
  flex-shrink: 0;
}

.search-card {
  margin-bottom: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.list-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.course-cover {
  border-radius: 4px;
  object-fit: cover;
}

.price {
  color: #f5222d;
  font-weight: 600;
}

.sales-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.sales-count {
  font-size: 14px;
  color: #333;
}

.sales-rate {
  width: 60px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    gap: 16px;
  }
  
  .header-left h2 {
    font-size: 20px;
  }
  
  .search-card .ant-form-item {
    margin-bottom: 16px;
  }
}

@media (max-width: 480px) {
  .page-header {
    margin-bottom: 16px;
  }
  
  .search-card,
  .list-card {
    margin-bottom: 16px;
  }
}
</style>
